package com.play.ballen.utils;

import android.content.Context;
import android.os.Handler;

import com.xuexiang.xupdate.XUpdate;
import com.xuexiang.xupdate.service.OnFileDownloadListener;

import java.io.File;

public class ApkDownManger {

    private int state = 0;//0-待下载 1-正在下载  2-已下载 3-取消 4失败

    //监听事件设置
    private Context context;
    private String downPath;
    private String savePath;
    private String apkPath;
    private Handler handler;

    public ApkDownManger(Context context, String downPath, String savePath) {
        this.handler=new Handler();
        this.context=context;
        this.downPath = downPath;
        this.savePath = savePath;
    }

    public int getState() {
        return state;
    }

    public String getSavePath() {
        return apkPath;
    }

    public void startDown(final IDownBack downBack) {
        this.state=1;
        downBack.onBack(state,0);
        XUpdate.newBuild(context)
                .apkCacheDir(savePath) //设置下载缓存的根目录
                .build()
                .download(downPath, new OnFileDownloadListener() {   //设置下载的地址和下载的监听
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onProgress(final float progress, long total) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                downBack.onBack(state,(int)(progress));
                            }
                        });
                    }

                    @Override
                    public boolean onCompleted(File file) {
                        state=2;
                        apkPath=file.getPath();
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                downBack.onBack(state,0);
                            }
                        });
                        return false;
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        state=3;
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                downBack.onBack(state,0);
                            }
                        });
                    }
                });
    }

    public interface IDownBack {
        void onBack(int state,int progress);
    }

}
